package com.dd.keel.core.framework.server;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 请求对象队列
 * @author Kevin.XU
 *
 */
public class ServerReqObjQueue {

	final static private Logger LOGGER = LoggerFactory.getLogger(ServerReqObjQueue.class);
	
	private int max_size = 1000;         /**default value*/
	private BlockingQueue<ServerTaskObj> queue = null;	
	
	public ServerReqObjQueue(int max_size)
	{
		if(max_size>0) this.max_size = max_size;
		this.queue = new LinkedBlockingQueue<ServerTaskObj>(this.max_size);
	}
	
	/**
	 * 把请求对象放入队列
	 * @param taskObj
	 * @throws Exception
	 */
	public void putReq(ServerTaskObj taskObj) throws Exception
	{
		boolean flag = false;
		try {
			int size = size();
			if((double)size/max_size>0.8)
			{
				LOGGER.warn("NOTICE!!request queue size is {}",size);
			}else{
				LOGGER.trace("request queue size is {}",size);
			}
			queue.put(taskObj);
			flag = true;
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			throw e;
		}
	}
	
	/**
	 * 从队列中取出请求对象
	 * @return
	 * @throws Exception
	 */
	public ServerTaskObj getReq() throws Exception
	{
		ServerTaskObj taskObj = null;
		try {
			LOGGER.trace("handle, request queue size is {}",size());
			taskObj = queue.take();
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			throw e;
		}
		return taskObj;
	}
	
	/**
	 * 返回请求对象的数目
	 * @return
	 */
	public int size()
	{
		return queue.size();
	}
	
	/**
	 * 清除对象
	 */
	public void clear()
	{
		queue.clear();
	}
	
}
